package com.example.rbq.coord

import android.R.attr
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toolbar
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.widget.NestedScrollView
import com.google.android.material.appbar.AppBarLayout


class HeadImageBehavior @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : CoordinatorLayout.Behavior<ImageView>(context, attrs) {

    /**
     * 处于中心时候原始X轴
     */
    private var mOriginalHeaderX = 0

    /**
     * 处于中心时候原始Y轴
     */
    private var mOriginalHeaderY = 0

    override fun onLayoutChild(
        parent: CoordinatorLayout,
        child: ImageView,
        layoutDirection: Int
    ): Boolean {
        return super.onLayoutChild(parent, child, layoutDirection)
    }

    override fun layoutDependsOn(
        parent: CoordinatorLayout,
        child: ImageView,
        dependency: View
    ): Boolean {
        return dependency is AppBarLayout
    }

    override fun onDependentViewChanged(
        parent: CoordinatorLayout,
        child: ImageView,
        dependency: View
    ): Boolean {
        // 计算X轴坐标
        if (mOriginalHeaderX == 0) {
            this.mOriginalHeaderX = (dependency.width / 2) - (child.width / 2)
        }
        // 计算Y轴坐标
        if (mOriginalHeaderY == 0) {
            mOriginalHeaderY = dependency.height - child.height;
        }
        //X轴百分比

        //X轴百分比
        var mPercentX: Float = Math.abs(dependency.y / mOriginalHeaderX)
        if (mPercentX >= 1) {
            mPercentX = 1f
        }

        var x = mOriginalHeaderX + mOriginalHeaderX * mPercentX
        if (x >= dependency.width - child.width * 2) {
            x = (dependency.width - child.width * 2).toFloat()
        }

        //Y轴百分比
        var mPercentY: Float = Math.abs(dependency.y / mOriginalHeaderY)
        if (mPercentY >= 1) {
            mPercentY = 1f
        }
        var y = mOriginalHeaderY - mOriginalHeaderY * mPercentY

        // 调整位置
        child.x = x
        child.y = y

        if (y == 0f){
            val param = child.layoutParams
            parent.removeView(child)
            parent.addView(child,param)
        }
        Log.e("xiao","x:${child.x},y:${child.y}")

//        // 放大缩小
//        child.scaleX = 1 - mPercentY
//        child.scaleY = 1 - mPercentY
        return true
    }

}